package com.example.blog.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class JWTutil {
    private static long expiration  = 30*60*1000;//设置30分钟过期
    private static String setSigningKey = "tkxN7pOT3U8GpuwhiHu3QDSFBVGQD9oHWmeF8xtYeeU=";
    private static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(setSigningKey));
    /**
     * 生成令牌
     * @param clamis
     * @return 令牌
     */
    public static String genJWT(Map<String,Object> clamis){
        return Jwts.builder()
                .setClaims(clamis)
                .setExpiration(new Date(System.currentTimeMillis()+expiration))
                .signWith(key)
                .compact();
    }

    /**
     * 校验令牌
     * @param token
     * @return Clamis
     */
    public static Claims verify(String token){
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        }catch (ExpiredJwtException e){
            log.error("token过期校验失败,token:{}",token);
        }catch (Exception e){
            log.error("token校验失败,token:{}",token);
        }
        return claims;
    }

    //通过token获取userId
    public static Integer getUserIdByToken(String token){
        Claims claims = JWTutil.verify(token);
        Assert.notNull(token,"token不合法");
        return (Integer) claims.get("id");
    }
}
